package com.lovo.order.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lovo.common.bean.Order;
import com.lovo.common.bean.OrderProduct;
import com.lovo.common.bean.Product;
import com.lovo.common.result.GlobalHandleException;
import com.lovo.common.result.Result;
import com.lovo.common.result.ResultCode;
import com.lovo.common.util.RedisUtil;
import com.lovo.order.dao.OrderProductMapper;
import com.lovo.order.form.ProductForm;
import com.lovo.order.service.OrderService;
import com.lovo.order.dao.OrderMapper;
import com.lovo.order.service.ProductService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;

/**
* @author BDK-THINKPAD
* @description 针对表【t_order】的数据库操作Service实现
* @createDate 2023-08-17 09:45:55
*/
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order>
    implements OrderService{
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private DiscoveryClient discoveryClient;
    @Autowired
    private ProductService productService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private OrderProductMapper orderProductMapper;
    @Override
    public void addOrder(Order order) {
        // 向注册中心获取服务的信息
//        List<ServiceInstance> serviceInstances = discoveryClient.getInstances("shop-product");
//        ServiceInstance serviceInstance = serviceInstances.get(new Random().nextInt(serviceInstances.size()));
//        String url = serviceInstance.getHost() + ":" + serviceInstance.getPort();
//        System.out.println("url:" + url);
//        String url = "shop-product";
        List<OrderProduct> orderProducts = order.getOrderProducts();
        List ids = orderProducts.stream().map(item -> item.getId()).toList();
//        String ids = orderProducts.stream().map(item -> "ids=" + item.getId()).collect(Collectors.joining("&"));
//        Result result = restTemplate.getForObject("http://" + url + "/products/ids?" + ids, Result.class);
//
//        List<Map> data = (List) result.getData();
//        System.out.println(data.get(0).get("name"));

        ProductForm productForm = new ProductForm();
        productForm.setIds(ids);
        Object result = productService.getByIds(ids);
//        Object result = productService.getById(order.getOrderProducts().get(0).getId());
        System.out.println("result:" + result);
    }

    @Override
    @GlobalTransactional(rollbackFor = GlobalHandleException.class)
    public void addSeckillOrder(String messageId, Integer userId, Integer productId) throws GlobalHandleException {
        // 判断幂等性
        if(redisUtil.hasKey(messageId)){
            return;
        }
        // 判断库存是否足够
        Object productCount = redisUtil.get("product_" + productId);
        if(productCount == null || Integer.parseInt(productCount.toString()) <= 0){
            throw new GlobalHandleException(ResultCode.COMMODITY_NOT_ENOUGH);
        }
        // 生成订单编号
        String orderNumber = redisUtil.generateOrderId();
        redisUtil.set(messageId,orderNumber,60 * 60);

        // 根据商品ID查询商品数据
        Map productMap = (Map) productService.getById(productId);

        Product product = new Product();
        product = BeanUtil.fillBeanWithMap((Map) productMap.get("data"),product,true);
        System.out.println(product);

        // 生成订单
        Order order = new Order();
        order.setNumber(orderNumber);
        order.setUserId(userId);
        order.setPrice(product.getPrice());
        order.setCreateTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());

        this.getBaseMapper().insert(order);
        // 生成订单商品数据
        OrderProduct orderProduct = new OrderProduct();
        orderProduct.setName(product.getName());
        orderProduct.setCount(product.getCount());
        orderProduct.setPrice(product.getPrice());
        orderProduct.setOrderId(order.getId());
        orderProduct.setImagePath(product.getImagePath());
        orderProduct.setCreateTime(LocalDateTime.now());
        orderProduct.setUpdateTime(LocalDateTime.now());
        orderProductMapper.insert(orderProduct);

        // 修改商品库存
        product.setCount(product.getCount() - 1);
        productService.update(productId,product);
//        int i = 10 / 0;
        // 缓存和库存同步
        redisUtil.set("product_" + productId,product.getCount());

    }


}




